package com.lix.service.workflow.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lix.auth.filter.TokenVerificationFilter;
import com.lix.base.BaseResult;
import com.lix.mapper.LoanMapper;
import com.lix.pojo.model.Leave;
import com.lix.pojo.model.Loan;
import com.lix.service.workflow.IBusinessStatusService;
import com.lix.service.workflow.ILoanService;
import com.lix.utils.UserUtils;
import com.lix.vo.workflow.req.LoanReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan> implements ILoanService {

    @Autowired
    private IBusinessStatusService businessStatusService;
    @Autowired
    private UserUtils userUtils;
    @Override
    public BaseResult add(Loan loan) {
        // 1. 新增借款信息
        // 当前登录用户即为申请人
        loan.setUserId(userUtils.getUsername());
        int size = baseMapper.insert(loan);
        // 2. 新增借款业务状态：待提交
        if (size == 1) {
            businessStatusService.add(loan.getId());
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult listPage(LoanReq req) {
        if (StringUtils.isEmpty(req.getUsername())) {
            req.setUsername(userUtils.getUsername());
        }

        // 创建一个分页对象
        // 使用 req 中的分页参数
        Page<Loan> page = new Page<>(req.getPageNum(), req.getPageSize());
        // 调用分页查询
        IPage<Loan> resultPage  = baseMapper.getLoanAndStatusList(page, req);
        return BaseResult.ok(resultPage);
    }

    @Override
    public BaseResult update(Loan loan) {
        if (loan == null || StringUtils.isEmpty(loan.getId())) {
            return BaseResult.error("数据不合法");
        }
        // 查询原数据
        Loan entity = baseMapper.selectById(loan.getId());
        // 拷贝新数据
        BeanUtils.copyProperties(loan, entity);
        entity.setUpdateDate(new Date());
        baseMapper.updateById(entity);
        return BaseResult.ok();
    }
}
